const cdnDependencies = require('./dependencies-cdn')
const path = require('path')

const resolve = dir => path.join(__dirname, dir)
// CDN外链，会插入到index.html中
const externals = {}
cdnDependencies.forEach(item => {
  externals[item.name] = item.library
})
const cdn = {
  css: cdnDependencies.map(e => e.css).filter(e => e),
  js: cdnDependencies.map(e => e.js).filter(e => e)
}

module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
  productionSourceMap: false,
  devServer: {
    proxy: {
      // '/Admin': {
      //   target: 'http://youxiantec.xishuw.com',
      //   secure: false,
      //   changeOrigin: true
      // },
      '/Kanjia': {
        target: 'http://opentec.xishuw.cn',
        secure: false,
        changeOrigin: true
      },
      '/api': {
        target: 'https://job.xishuw.com',
        secure: false,
        changeOrigin: true
      },
      '/wap': {
        target: 'https://marry.xishuw.com',
        secure: false,
        changeOrigin: true
      }
    }
  },
  configureWebpack: config => {
    config.resolve.alias = { '@': resolve('src') }
    // 开发环境配置
    if (process.env.NODE_ENV === 'production') {
      // 移除 console
      config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
      // CDN
      config.externals = externals
      // GZIP
      const CompressionPlugin = require('compression-webpack-plugin')
      config.plugins.push(
        new CompressionPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
          threshold: 8192,
          minRatio: 0.8
        })
      )
    } else {
      // config.devtool = 'source-map'
    }
  },
  chainWebpack: config => {
    // cdn
    config.plugin('html').tap(args => {
      args[0].cdn = process.env.NODE_ENV === 'production' ? cdn : []
      return args
    })
    config.plugins
      .delete('prefetch')
      .delete('preload')
    // 分析工具
    if (process.env.npm_config_report) {
      config
        .plugin('webpack-bundle-analyzer')
        .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
    }
  }
}
